// pages/changeDetails/changeDetails.js
var base_url = getApp().globalData.base_url
var app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        categoryType: 1,
        categoryId: 6,
        accountTime: new Date().toLocaleDateString(),
        accountComment: "",
        accountAmount: 0.01,    // TODO 记得改成0

        radioItems: [
            { name: '收入', value: '0' },
            { name: '支出', value: '1', checked: true }
        ],
        // "工资", "兼职", "理财", "礼金", "其他"
        incomes: [],
        incomeIndex: 0,

        outcomes: [],
        // "餐饮", "购物", "日用", "交通", "蔬菜", "水果", "零食",
        //     "运动", "娱乐", "通讯", "服饰", "美容", "住房", "居家", "社交", "旅行",
        //     "数码", "烟酒", "医疗", "学习", "书籍", "宠物", "礼金", "办公", "维修",
        //     "捐赠", "快递"
        outcomeIndex: 0,
        isLoaded: false
    },


    radioChange: function (e) {
        console.log('radio发生change事件，携带value值为：', e.detail.value);

        var radioItems = this.data.radioItems;
        for (var i = 0, len = radioItems.length; i < len; ++i) {
            radioItems[i].checked = radioItems[i].value == e.detail.value;
        }

        this.setData({
            radioItems: radioItems,
            categoryType: e.detail.value
        });
    },

    bindDateChange: function (e) {
        this.setData({
            accountTime: e.detail.value
        })
    },

    bindIncomeCountryCodeChange: function (e) {
        let categoryName = this.data.incomes[Number(e.detail.value)]
        let categoryId = this.findCategoryIdByName(categoryName)
        this.setData({
            incomeIndex: e.detail.value,
            categoryId: categoryId
        })
    },
    bindOutcomeCategoryChange: function (e) {
        let categoryName = this.data.outcomes[Number(e.detail.value)]
        let categoryId = this.findCategoryIdByName(categoryName)
        this.setData({
            outcomeIndex: e.detail.value,
            categoryId: categoryId
        })
    },

    bindAccountAmountChange: function (e) {
        this.setData({
            accountAmount: Number(e.detail.value)
        })
    },

    bindInputChange: function (e) {
        this.setData({
            accountComment: e.detail.value
        })
    },

    submit_account: function () {

        let userId = app.globalData.userId;
        console.log(this.data.categoryId)

        // 数据校验
        if (isNaN(Number(this.data.accountAmount)) || this.data.accountAmount <= 0) {
            // TODO 弹出提示
            console.log("金额格式错误")
            return
        }
        if (this.data.accountComment.length > 4) {
            // TODO 弹出提示
            console.log("备注格式错误")
            return
        }

        let that = this;
        wx.request({
            url: base_url + '/users/accounts',
            data: {
                "userId": userId,
                "accountAmount": that.data.accountAmount,
                "accountType": that.data.categoryType,
                "categoryId": that.data.categoryId,
                "accountTime": new Date(that.data.accountTime).valueOf(),
                "accountComment": that.data.accountComment,
            },
            method: 'POST',
            header: {
                "content-type": 'application/x-www-form-urlencoded'
            },

            success(res) {
                if (res.data.resultCode == 200) {
                    wx.showToast({
                        title: '保存成功',
                        icon: 'success',
                        duration: 3000//持续的时间
                    })
                } else {
                    wx.showModal({
                        content: res.data.message
                    })
                }
            }
        })
    },

    onLoad() {
        this.getAndSetCategories()
    },

    getAndSetCategories() {
        var that = this;
        this.startLoad()
        wx.request({
            url: base_url + '/admins/categories',
            method: 'GET',
            success(res) {
                if (res.data.resultCode == 200) {
                    app.globalData.categories = res.data.data
                }
                // 生成收入支出数组并且渲染到本页面
                let categories = res.data.data;
                let incomes = [];
                let outcomes = [];
                categories.map(item => {
                    if (item.categoryType == 0) incomes.push(item.categoryName)
                    else outcomes.push(item.categoryName)
                })
                that.setData({
                    incomes: incomes,
                    outcomes: outcomes
                })
                that.data.isLoaded = true;
            },
            complete() {
                that.endLoad()
            }
        })
    },

    startLoad() {
        //在当前页面显示导航条加载动画
        wx.showNavigationBarLoading();
        //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
        wx.showLoading({
            title: '加载中...',
        })
    },

    endLoad() {
        //隐藏loading 提示框
        wx.hideLoading();
        //隐藏导航条加载动画
        wx.hideNavigationBarLoading();
    },

    onShow() {
        if (this.data.isLoaded) {
            let categories = app.globalData.categories
            let incomes = [];
            let outcomes = [];
            categories.map(item => {
                if (item.categoryType == 0) incomes.push(item.categoryName)
                else outcomes.push(item.categoryName)
            })
            this.setData({
                incomes: incomes,
                outcomes: outcomes
            })
        }
    },

    findCategoryIdByName(categoryName) {
        let categories = app.globalData.categories
        let categoryId;
        for (let i = 0; i < categories.length; i++) {
            if (categoryName == categories[i].categoryName) {
                categoryId = categories[i].categoryId
                break
            }
        }
        return categoryId
    },

    submitDetails: function () {
        if (isNaN(Number(this.data.accountAmount)) || this.data.accountAmount <= 0) {
            // TODO 弹出提示
            console.log("金额格式错误")
            wx.showToast({
                title: '金额格式错误',
                icon: 'false',
                duration: 1000//持续的时间
            })
            return
        }
        if (this.data.accountComment.length > 4) {
            // TODO 弹出提示
            wx.showToast({
                title: '备注格式错误',
                icon: 'fail',
                duration: 1000//持续的时间
            })
            console.log("备注格式错误")
            return
        }
        let that = this;
        let accountId = app.globalData.accountId
        wx.request({
            url: base_url + '/users/accounts',
            data: {
                "accountId": accountId,
                "accountAmount": that.data.accountAmount,
                "accountType": that.data.categoryType,
                "categoryId": that.data.categoryId,
                "accountTime": new Date(that.data.accountTime).valueOf(),
                "accountComment": that.data.accountComment,
            },
            method: 'PUT',
            header: {
                "content-type": 'application/x-www-form-urlencoded'
            },

            success(res) {
                if (res.data.resultCode == 200) {
                    wx.showToast({
                        title: '保存成功',
                        icon: 'success',
                        duration: 1000//持续的时间
                    })
                    // 重新请求一次details



                    wx.navigateBack({
                        delta: 0,
                    })
                } else {
                    wx.showModal({
                        content: res.data.message
                    })
                }
            },
            fail: (res) => {
                console.log(res)
            },
        })

    },

})